/*************************************************************************
	> File Name: 5-4-b.c
	> Author: Angel Criss
	> Mail: abbytsing@gmail.com 
	> Created Time: Thu Jul 24 16:12:38 2014
 ************************************************************************/
//  I wonder why?

#include "ch-5.h"

int _dup2(int fdold,int fdnew)
{
    int *tmp;
    int i=0;

    if(fdold==fdnew)
        return fdnew;

    close(fdnew);

    tmp=(int *)malloc(sizeof(int)*(fdnew>fdold?fdnew:fdold));

    do
    {
        tmp[i]=dup(fdold); // dup(fdold)
    }while(tmp[i++]<fdnew-1);

    fdnew=dup(fdold);

    while(i)
    {
        if(tmp[--i]>0)
            close(tmp[i]);
    }

    free(tmp);

    return fdnew;
}

int main(int argc,char *argv[])
{
    int newfd=-1;

    newfd=_dup2(1,6);

    printf("The new fd is: %d\n",newfd);

    exit(0);
}
